// 社区动态相关API
import type { Data } from './index'

// 社区动态数据接口
export interface Post {
  id: number
  username: string
  avatar: string
  content: string
  like: number
  images: string
  createTime: string
  arrayComment: Comment[]
}

// 评论数据接口
export interface Comment {
  id: number
  postId: number
  userId: number
  username: string
  replyToUserId: number | null
  replyToUsername: string | null
  content: string
  createTime: string
}

// 点赞数据接口
export interface Like {
  id: number
  postId: number
  userId: number
  isLike: string
  createTime: string
}

// 响应数据接口
export interface PostResponse {
  code: number
  info: string
  data: Post[]
}

// 点赞响应接口
export interface LikeResponse {
  code: number
  info: string
  data: Like[]
}

/**
 * 查询社区动态（使用专门的接口）
 * 获取用户发布的社区动态列表
 */
export const queryPostsShi = (): Promise<UniApp.RequestSuccessCallbackResult> => {
  const token = uni.getStorageSync('token')
  return uni.request({
    url: 'http://localhost:8000/api/post/queryshi',
    method: 'GET',
    header: {
      token: token,
    },
  })
}

/**
 * 发布社区动态
 * @param postData 动态内容数据
 */
export const createPost = (postData: {
  content: string
  images?: string
}): Promise<UniApp.RequestSuccessCallbackResult> => {
  const token = uni.getStorageSync('token')
  return uni.request({
    url: 'http://localhost:8000/api/post/create',
    method: 'POST',
    data: postData,
    header: {
      token: token,
      'Content-Type': 'application/json',
    },
  })
}

/**
 * 点赞动态
 * @param postId 动态ID
 */
export const likePost = (postId: number): Promise<UniApp.RequestSuccessCallbackResult> => {
  const token = uni.getStorageSync('token')

  // 从本地存储获取用户ID
  let userId = null
  const userInfo = uni.getStorageSync('userInfo')

  if (userInfo) {
    try {
      const userInfoObj = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo
      userId = userInfoObj.id
    } catch (e) {
      console.error('解析用户信息失败:', e)
      return Promise.reject(new Error('获取用户ID失败'))
    }
  }

  if (!userId) {
    console.error('点赞失败: 用户ID不存在')
    return Promise.reject(new Error('用户ID不存在'))
  }

  // 构建点赞请求数据
  const likeDto = {
    postId,
    userId,
  }

  console.log('发送点赞请求:', likeDto)

  return uni.request({
    url: 'http://localhost:8000/api/like/like',
    method: 'POST',
    data: likeDto,
    header: {
      token: token,
      'Content-Type': 'application/json',
    },
  })
}

/**
 * 上传图片
 * @param filePath 图片路径
 */
export const uploadImage = (filePath: string): Promise<any> => {
  const token = uni.getStorageSync('token')
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: 'http://localhost:8000/api/upload/image',
      filePath,
      name: 'file',
      header: {
        token: token,
      },
      success: (res) => {
        // 将字符串响应数据转为JSON对象
        try {
          const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
          resolve(data)
        } catch (e) {
          reject(new Error('解析响应数据失败'))
        }
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

/**
 * 获取用户点赞的帖子
 */
export function findLikes() {
  const token = uni.getStorageSync('token') || ''

  // 尝试从不同的存储位置获取用户ID
  let userId = null

  // 如果没有直接存储的userId，尝试从userInfo中获取
  if (!userId) {
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo) {
      try {
        const userInfoObj = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo
        userId = userInfoObj.id
      } catch (e) {
        console.error('解析用户信息失败:', e)
      }
    }
  }

  console.log('查询点赞列表，用户ID:', userId)

  if (!userId) {
    console.error('获取点赞数据失败: 用户ID不存在')
    return Promise.reject(new Error('用户ID不存在'))
  }

  return uni.request({
    url: 'http://localhost:8000/api/like/findlike',
    method: 'POST',
    data: { userId },
    header: {
      token: token,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  })
}

/**
 * 添加评论（使用新的评论接口）
 * @param commentData 评论数据
 */
export interface CommentRequest {
  postId: number
  content: string
  replyToUserId?: number | null
  replyToUsername?: string | null
}

export const insertComment = (
  commentData: CommentRequest,
): Promise<UniApp.RequestSuccessCallbackResult> => {
  const token = uni.getStorageSync('token')
  const userInfo = uni.getStorageSync('userInfo')

  // 从本地存储获取用户信息
  let userId = null
  let username = ''

  if (userInfo) {
    const userInfoObj = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo
    userId = userInfoObj.id
    username = userInfoObj.username || userInfoObj.nickname || ''
  }

  // 构建请求数据
  const requestData = {
    postId: commentData.postId,
    content: commentData.content,
    userId: userId,
    username: username,
    replyToUserId: commentData.replyToUserId || null,
    replyToUsername: commentData.replyToUsername || null,
  }

  console.log('发送评论数据:', requestData)

  return uni.request({
    url: 'http://localhost:8000/api/comments/insertcomment',
    method: 'POST',
    data: requestData,
    header: {
      token: token,
      'Content-Type': 'application/json',
    },
  })
}

/**
 * 查询我的动态
 * 获取当前登录用户发布的动态列表
 */
export const queryMyPosts = (): Promise<UniApp.RequestSuccessCallbackResult> => {
  const token = uni.getStorageSync('token')
  const userInfo = uni.getStorageSync('userInfo')
  let userId = null

  if (userInfo) {
    const userInfoObj = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo
    userId = userInfoObj.id
  }

  if (!userId) {
    return Promise.reject(new Error('未找到用户ID'))
  }

  return uni.request({
    url: 'http://localhost:8000/api/post/querybyuserId',
    method: 'POST',
    data: { userId },
    header: {
      token: token,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  })
}

/**
 * 删除动态
 * @param postId 动态ID
 */
export const deletePost = (postId: number): Promise<UniApp.RequestSuccessCallbackResult> => {
  const token = uni.getStorageSync('token')
  return uni.request({
    url: `http://localhost:8000/api/post/delete/${postId}`,
    method: 'POST',
    header: {
      token: token,
    },
  })
}

/**
 * 获取用户评论
 * 获取当前用户发布的所有评论
 */
export const getUserComments = (): Promise<UniApp.RequestSuccessCallbackResult> => {
  const token = uni.getStorageSync('token')
  const userInfo = uni.getStorageSync('userInfo')
  let userId = null

  if (userInfo) {
    const userInfoObj = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo
    userId = userInfoObj.id
  }

  if (!userId) {
    return Promise.reject(new Error('未找到用户ID'))
  }

  return uni.request({
    url: 'http://localhost:8000/api/comments/getUserComments',
    method: 'POST',
    data: { userId },
    header: {
      token: token,
      'Content-Type': 'application/json',
    },
  })
}

/**
 * 查询用户评论（使用新的接口）
 * 通过GET方式获取当前用户的评论列表
 */
export const queryComment = (): Promise<UniApp.RequestSuccessCallbackResult> => {
  const token = uni.getStorageSync('token')
  return uni.request({
    url: 'http://localhost:8000/api/comments/querycomment',
    method: 'GET',
    header: {
      token: token,
    },
  })
}

/**
 * 删除评论
 * @param id 评论ID
 */
export const deleteComment = (id: number): Promise<UniApp.RequestSuccessCallbackResult> => {
  const token = uni.getStorageSync('token')
  return uni.request({
    url: `http://localhost:8000/api/comments/deletecomment/${id}`,
    method: 'POST',
    header: {
      token: token,
    },
  })
}
